<?php

namespace app\api\controller;

use app\common\controller\Logined;
use app\common\service\BalanceService;

use think\Db;

//兑换
class Exchange extends Logined{

	/*
	兑换列表
	*/
	public function exList(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数用户ID(uid)');
		}
		$data = model('ExchangeConfigModel')->exList($uid);
		if($data){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}


	/*
	单个钱包
	 */
	public function exOne(){
		$uid = $this->uid;
		$wid  = P('wid');
		if(empty($uid)){
			$this->retData(1,'缺少参数用户ID(uid)');
		}
		if(empty($wid)){
			$this->retData(1,'缺少参数钱包ID(wid)');
		}
		$data = model('ExchangeConfigModel')->exOne($uid,$wid);
		if($data){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	兑换
	*/
	public function exchange(){
		if(C('exchange_status') != 1){
			$this->retData(1,'闪兑功能维护中~~');
		}
		$uid       = $this->uid;
		$id        = P('id');
		$amount    = P('amount');
		$paypass   = P('paypass');
		if(empty($uid)){
			$this->retData(1,'缺少参数用户ID(uid)');
		}
		if(empty($id)){
			$this->retData(1,'缺少参数配置ID(id)');
		}
		if(empty($amount)){
			$this->retData(1,'缺少参数数量(amount)');
		}
		if(empty($paypass)){
			$this->retData(1,'缺少参数交易密码(paypass)');
		}

		if($amount <= 0){
			$this->retData(1,'闪兑数量有误，请重新输入');
		}
		if ($paypass != $this->user_info['paypass']) {
            $this->retData(1,'密码错误');
        }
		//配置是否存在
		$config = model('ExchangeConfigModel')->getOneConfig($id,$uid);

		if(empty($config)){
			$this->retData(1,'未找到闪兑配置');
		}
		$wid    = $config['wid'];
		$to_wid = $config['to_wid'];
		if($amount < $config['min_amount']){
			$this->retData(1,'最低'.$config['min_amount'].'起兑');
		}
		if($config['from_price']<=0 || $config['to_price']<=0){
			$this->retData(1,'币种价格有误');
		}
		if ($config['balance'] < $amount) {
			$this->retData(1,'余额不足');
		}
		if ($config['fee_type'] == 1) {
			$fee = $amount * $config['fee'];
		} else {
			$fee = $config['fee'];
		}
		$left_amount = $amount-$fee;
		if ($left_amount<=0) {
			$this->retData(1,'手续费不足');
		}
		$rate = $config['from_price']/$config['to_price'];
		$to_amount = $left_amount * $rate;
		
		Db::startTrans();
		//添加兑换记录
		$res1 = model('ExchangeRecordModel')->addRecord($uid,$wid,$to_wid,$amount,$fee,$to_amount,$rate);
		//闪兑兑出
		$res2 = BalanceService::updateBalance($uid,$wid,-$amount,'兑换(含手续费'.
			$fee.')',51,$res1);
		//兑换兑入
		$res3 = BalanceService::updateBalance($uid,$to_wid,$to_amount,'兑换',52,$res1);
		$res4 = $res5 = $res6 = 1;
		if($res1 && $res2 && $res3 && $res4 && $res5 && $res6){
			Db::commit();
			$this->retData(0,'兑换成功');
		} else {
			Db::rollback();
			$this->retData(1,'兑换失败');
		}
	}

	public function ethPrice(){
		$data = C('eth_price');
		$this->retData(0,'success',$data);
	}
}